/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wuhenzhizao.slice;

import com.wuhenzhizao.bean.Product;
import com.wuhenzhizao.ProductSkuDialog;
import com.wuhenzhizao.ResourceTable;
import com.wuhenzhizao.sku.bean.Sku;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.Button;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Optional;

/**
 * 主页
 *
 * @author wuhenzhizao
 * @since 2017-08-02
 */
public class MainAbilitySlice extends AbilitySlice {
    private static HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, "TAG");

    private static final int ZERO = 0;
    private static final int TWO = 2;
    private static final int ONE_HUNDRED = 100;
    private static final int THREE_HUNDRED_AND_FIFTY = 350;
    private static final int SEVEN_HUNDRED = 700;
    private static final float ONE_POINT_FIVE = 1.5f;
    private static final float ZERO_POINT_TWO = 0.2f;
    private ProductSkuDialog dialog;
    private int shoppingCartNum = 0;
    private Text tvShoppingCartNum;
    private Image ivAddCartAnim;
    private DependentLayout dependentLayout;
    private int[] startLocation;
    private int[] bottomCartLocation;
    private Image imageClose;
    private AnimatorGroup animatorGroup;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
        } catch (IllegalArgumentException e) {
            e.getMessage();
        }
        super.setUIContent(ResourceTable.Layout_ability_main);

        initComponent();
    }

    private void initComponent() {
        dependentLayout = (DependentLayout) findComponentById(ResourceTable.Id_container);
        imageClose = (Image) findComponentById(ResourceTable.Id_image_close);
        tvShoppingCartNum = (Text) findComponentById(ResourceTable.Id_tv_shopping_cart_num);
        ivAddCartAnim = (Image) findComponentById(ResourceTable.Id_iv_add_cart_anim);
        Button btn = (Button) findComponentById(ResourceTable.Id_btn);

        btn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // 获取屏幕宽 高
                Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(getContext());
                DisplayAttributes displayAttributes = display.get().getAttributes();
                int centerX = displayAttributes.width / TWO;
                int centerY = displayAttributes.height / TWO;
                int rightX = displayAttributes.width - ONE_HUNDRED;
                int rightY = 0;
                /**
                 * 开始动画位置的X、Y坐标
                 */
                startLocation = new int[]{centerX, centerY};
                /**
                 * 这是用来存储动画结束位置的X、Y坐标
                 */
                bottomCartLocation = new int[]{rightX, rightY};

                HiLog.error(logLabel, "TAG--endX-" + startLocation[0] + "``"
                        + startLocation[1] + ",-endY-" + bottomCartLocation[0] + "``" + bottomCartLocation[1]);

                showSkuDialog();
            }
        });

        imageClose.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                getAbility().terminateAbility();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void showSkuDialog() {
        if (dialog == null) {
            dialog = new ProductSkuDialog(this);
            dialog.setData(Product.get(this),
                    new ProductSkuDialog.Callback() {
                        @Override
                        public void onAdded(Sku sku, int quantity) {
                            shoppingCartNum += quantity;

                            // 执行动画
                            addToCartAnim();
                        }
                    });
        }
        dialog.show();
    }

    private void addToCartAnim() {
        DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig();
        layoutConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
        ivAddCartAnim.setLayoutConfig(layoutConfig);

        ivAddCartAnim.setVisibility(Component.VISIBLE);
        animatorGroup = new AnimatorGroup();

        AnimatorProperty expandAnimation = ivAddCartAnim.createAnimatorProperty();
        expandAnimation.scaleXBy(1.0f).scaleXFrom(ONE_POINT_FIVE)
                .scaleYBy(1.0f).scaleYFrom(ONE_POINT_FIVE).setDuration(THREE_HUNDRED_AND_FIFTY);
        expandAnimation.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);

        AnimatorProperty collapseAnimation = ivAddCartAnim.createAnimatorProperty();
        collapseAnimation.scaleXBy(ZERO_POINT_TWO).scaleXFrom(1.0f)
                .scaleYBy(ZERO_POINT_TWO).scaleXFrom(1.0f).setDuration(SEVEN_HUNDRED).setDelay(THREE_HUNDRED_AND_FIFTY);
        collapseAnimation.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);

        // 计算位移 动画位移的X坐标  动画位移的y坐标
        int endX = bottomCartLocation[0] - startLocation[0];
        int endY = bottomCartLocation[1] - startLocation[1];

        HiLog.error(logLabel, "TAG--endX-" + endX + ",-endY-" + endY);
        AnimatorProperty translateAnimationX = ivAddCartAnim.createAnimatorProperty();
        translateAnimationX.moveFromX(startLocation[0]).moveToX(bottomCartLocation[0])
                .moveFromY(startLocation[1]).moveToY(bottomCartLocation[1])
                .setDuration(SEVEN_HUNDRED).setDelay(THREE_HUNDRED_AND_FIFTY);

        AnimatorProperty alphaAnimation = ivAddCartAnim.createAnimatorProperty();
        alphaAnimation.alpha(ZERO_POINT_TWO).alphaFrom(1.0f)
                .setDuration(SEVEN_HUNDRED).setDelay(THREE_HUNDRED_AND_FIFTY);

        animatorGroup.runParallel(expandAnimation, translateAnimationX, alphaAnimation, collapseAnimation);

        initAnimationListener();
        animatorGroup.start();
    }

    private void initAnimationListener() {
        animatorGroup.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
            }

            @Override
            public void onStop(Animator animator) {
            }

            @Override
            public void onCancel(Animator animator) {
                ivAddCartAnim.setVisibility(Component.INVISIBLE);
            }

            @Override
            public void onEnd(Animator animator) {
                ivAddCartAnim.setVisibility(Component.INVISIBLE);
                tvShoppingCartNum.setVisibility(Component.VISIBLE);
                tvShoppingCartNum.setText(String.valueOf(shoppingCartNum));
            }

            @Override
            public void onPause(Animator animator) {
            }

            @Override
            public void onResume(Animator animator) {
            }
        });
    }
}
